"use client"

import { useState, useEffect } from 'react'

interface ConnectGameProps {
  targetChar: string
  onGameEnd: (score: number, correct: number, total: number) => void
}

interface WordCard {
  id: number
  content: string
  type: 'character' | 'pinyin'
  isSelected: boolean
  isMatched: boolean
  pairId: number
}

export function ConnectGame({ targetChar, onGameEnd }: ConnectGameProps) {
  const [cards, setCards] = useState<WordCard[]>([])
  const [selectedCards, setSelectedCards] = useState<number[]>([])
  const [score, setScore] = useState(0)
  const [timeLeft, setTimeLeft] = useState(60)
  const [level, setLevel] = useState(1)
  const [gameStarted, setGameStarted] = useState(false)

  // 初始化卡片
  useEffect(() => {
    const wordPairs = [
      { character: '池', pinyin: 'chí' },
      { character: 'bái', pinyin: 'bái' },
      { character: '木', pinyin: 'mù' },
      { character: '白', pinyin: 'bái' },
      { character: '土', pinyin: 'tǔ' },
      { character: 'zhí', pinyin: 'zhí' },
      { character: 'mù', pinyin: 'mù' },
      { character: '支', pinyin: 'zhī' },
      { character: '火', pinyin: 'huǒ' },
      { character: '地', pinyin: 'dì' },
      { character: '水', pinyin: 'shuǐ' },
      { character: '也', pinyin: 'yě' },
      { character: 'yè', pinyin: 'yè' },
      { character: '皮', pinyin: 'pí' },
      { character: 'pí', pinyin: 'pí' },
      { character: '的', pinyin: 'de' }
    ]

    const gameCards: WordCard[] = wordPairs.map((item, index) => ({
      id: index,
      content: item.character,
      type: item.character.length === 1 && /[\u4e00-\u9fff]/.test(item.character) ? 'character' : 'pinyin',
      isSelected: false,
      isMatched: false,
      pairId: Math.floor(index / 2)
    }))

    setCards(gameCards)
  }, [])

  // 计时器
  useEffect(() => {
    if (gameStarted && timeLeft > 0) {
      const timer = setTimeout(() => {
        setTimeLeft(prev => prev - 1)
      }, 1000)
      return () => clearTimeout(timer)
    } else if (timeLeft === 0) {
      onGameEnd(score, cards.filter(c => c.isMatched).length / 2, cards.length / 2)
    }
  }, [timeLeft, gameStarted, score, cards, onGameEnd])

  // 处理卡片点击
  const handleCardClick = (cardId: number) => {
    if (!gameStarted) setGameStarted(true)
    
    const card = cards.find(c => c.id === cardId)
    if (!card || card.isMatched) return

    if (selectedCards.includes(cardId)) {
      // 取消选择
      setSelectedCards(prev => prev.filter(id => id !== cardId))
      setCards(prev => prev.map(c => 
        c.id === cardId ? { ...c, isSelected: false } : c
      ))
    } else {
      // 选择卡片
      setSelectedCards(prev => [...prev, cardId])
      setCards(prev => prev.map(c => 
        c.id === cardId ? { ...c, isSelected: true } : c
      ))
    }
  }

  const resetGame = () => {
    setSelectedCards([])
    setScore(0)
    setTimeLeft(60)
    setGameStarted(false)
    setCards(prev => prev.map(c => ({ ...c, isSelected: false, isMatched: false })))
  }

  return (
    <div className="h-full flex flex-col bg-white rounded-2xl p-6 relative">
      {/* 游戏标题和关闭按钮 */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center space-x-3">
          <div className="w-8 h-8 bg-pink-500 rounded-lg flex items-center justify-center">
            <span className="text-white text-lg">🔗</span>
          </div>
          <h3 className="text-xl font-bold text-gray-800">汉字连连看</h3>
        </div>
        <button
          onClick={() => onGameEnd(score, cards.filter(c => c.isMatched).length / 2, cards.length / 2)}
          className="w-8 h-8 bg-red-500 rounded-full flex items-center justify-center text-white hover:bg-red-600 transition-colors"
        >
          ✕
        </button>
      </div>

      {/* 游戏状态栏 */}
      <div className="grid grid-cols-3 gap-4 mb-6">
        <div className="text-center">
          <div className="text-2xl font-bold text-gray-800">{score}</div>
          <div className="text-sm text-gray-600">得分</div>
        </div>
        <div className="text-center">
          <div className="text-2xl font-bold text-gray-800">
            {Math.floor(timeLeft / 60).toString().padStart(2, '0')}:
            {(timeLeft % 60).toString().padStart(2, '0')}
          </div>
          <div className="text-sm text-gray-600">时间</div>
        </div>
        <div className="text-center">
          <div className="text-2xl font-bold text-gray-800">{level}</div>
          <div className="text-sm text-gray-600">关卡</div>
        </div>
      </div>
      
      {/* 游戏区域 */}
      <div className="flex-1 flex items-center justify-center">
        <div className="grid grid-cols-6 gap-3 max-w-2xl">
          {cards.map((card) => (
            <div
              key={card.id}
              onClick={() => handleCardClick(card.id)}
              className={`
                w-20 h-16 rounded-xl flex items-center justify-center cursor-pointer
                transition-all duration-300 transform hover:scale-105 shadow-lg
                ${card.isMatched
                  ? 'bg-gray-300 text-gray-500 cursor-not-allowed'
                  : card.isSelected
                  ? 'bg-gradient-to-br from-blue-400 to-blue-500 text-white scale-105'
                  : 'bg-gradient-to-br from-pink-400 to-pink-500 hover:from-pink-500 hover:to-pink-600 text-white'
                }
              `}
            >
              <span className="text-sm font-bold text-center px-1">
                {card.content}
              </span>
            </div>
          ))}
        </div>
      </div>

      {/* 底部控制按钮 */}
      <div className="flex justify-center space-x-4 mt-6">
        <button 
          onClick={() => setGameStarted(!gameStarted)}
          className="px-6 py-2 bg-blue-500 text-white rounded-full hover:bg-blue-600 transition-colors flex items-center space-x-2"
        >
          <span>{gameStarted ? '⏸️' : '▶️'}</span>
          <span>{gameStarted ? '暂停' : '开始'}</span>
        </button>
        <button 
          onClick={resetGame}
          className="px-6 py-2 bg-orange-500 text-white rounded-full hover:bg-orange-600 transition-colors flex items-center space-x-2"
        >
          <span>🔄</span>
          <span>重新开始</span>
        </button>
        <button className="px-6 py-2 bg-green-500 text-white rounded-full hover:bg-green-600 transition-colors flex items-center space-x-2">
          <span>⏭️</span>
          <span>下一关</span>
        </button>
        <button 
          onClick={() => onGameEnd(score, cards.filter(c => c.isMatched).length / 2, cards.length / 2)}
          className="px-6 py-2 bg-gray-500 text-white rounded-full hover:bg-gray-600 transition-colors flex items-center space-x-2"
        >
          <span>🚪</span>
          <span>退出游戏</span>
        </button>
      </div>
    </div>
  )
} 